package com.lcgroup.springdemo.demos.utils;

import com.lcgroup.springdemo.demos.tree.TreeNode;

import java.util.*;

public class TreeNodeUtils {


    public static TreeNode buildChildren(TreeNode root, List<TreeNode> sources) {
        List<TreeNode> children = new ArrayList<>();
        for (TreeNode source : sources) {
            if (source.getParentId() !=null && source.getParentId().equals(root.getId())) {
                children.add(buildChildren(source, sources));
            }
        }
        root.setChildren(children);
        return root;
    }


    //拍平
    public static List<TreeNode> buildFlat(TreeNode root) {
        List<TreeNode> res = new ArrayList<>();
        if (root.getChildren() == null || root.getChildren().isEmpty()){
            res.add(root);
        }else {
            res.add(root);
            for (TreeNode child : root.getChildren()) {
                res.addAll(buildFlat(child));
            }
        }
        return res;
    }

    //传入一个节点，找到它的顶层节点
    public static TreeNode findTop(TreeNode node, List<TreeNode> flatTreeList){
           while (node.getParentId() != null){
               TreeNode finalNode = node;
               node = flatTreeList.stream().filter(x -> x.getId().equals(finalNode.getParentId())).findFirst().orElse(new TreeNode());
           }
        return node;





    }

}
